
const limit = 2 * 1048576
// 图片压缩
export function picCompress(fileObj, callback) {
  const Quality = getQuality(fileObj.size)
  console.log(fileObj.size, limit, fileObj.size / limit, fileObj.size / limit > 2)
  // 图片大小大于2M进行图片压缩
  if (fileObj.size / limit > 2) {
    const reader = new FileReader()
    const image = new Image()
    image.onload = (imageEvent) => {
      const canvas = document.createElement('canvas') // 创建画布
      const context = canvas.getContext('2d') // 画布为2d
      const width = image.width * Quality // 图片宽度 * 压缩比例
      const height = image.height * Quality // 图片高度 * 压缩比例
      canvas.width = width // 画布宽度
      canvas.height = height // 画布宽度
      context.clearRect(0, 0, width, height)
      context.drawImage(image, 0, 0, width, height)
      const dataUrl = canvas.toDataURL(fileObj.type) // 图片转路径
      const blobData = dataURLtoBlob(dataUrl) // 图片转二进制
      callback(new window.File([blobData], fileObj.name))
    }
    reader.onload = e => { image.src = e.target.result }
    reader.readAsDataURL(fileObj)
  } else {
    // 压缩完成执行回调
    callback(fileObj)
  }
}

export function getQuality(size) {
  const str = String(limit / size)
  const num = Number(str.replace(/0/g, ''))
  console.log(num.toFixed(2))
  if (size / limit > 2) {
    return 1 - num.toFixed(2)
  } else {
    return 1
  }
}
export function dataURLtoBlob(dataURL) {
  var binary = atob(dataURL.split(',')[1])
  var array = []
  for (var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i))
  }
  return new Blob([new Uint8Array(array)])
}
